<template>
    <div v-loading="loading" class="offline-error-devices-page">
        <!-- 页面标题栏 -->
        <div class="page-title">
            <el-button link class="back-btn" @click="handleBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
            </el-button>
            <div class="title">离线及异常设备</div>
        </div>

        <div class="content">
            <DeviceStatusCards :isShowOnline="false" :device-list="allDevices" @filter-status="handleStatusFilter" />

            <div class="filter-section">
                <div class="left-filters">
                    <!-- 搜索框 -->
                    <el-input v-model="filterForm.searchText" placeholder="搜索设备编号、位置..." prefix-icon="Search"
                        clearable />

                    <el-select v-model="filterForm.deviceStatus" placeholder="设备状态" clearable filterable>
                        <el-option label="全部状态" value="" />
                        <el-option label="离线" value="offline" />
                        <el-option label="异常" value="error" />
                    </el-select>

                    <el-select v-model="filterForm.deviceType" placeholder="设备类型" clearable filterable>
                        <el-option label="全部类型" value="" />
                        <el-option label="水表" value="1" />
                        <el-option label="电表" value="2" />
                        <el-option label="其他设备" value="3" />
                    </el-select>

                    <el-select v-model="filterForm.area" placeholder="区域" clearable filterable>
                        <el-option label="全部区域" value="" />
                        <el-option v-for="area in areaStore.areas" :key="area.id" :label="area.name" :value="area.id" />
                    </el-select>
                </div>
            </div>

            <!-- 空状态展示 -->
            <div v-if="filteredDeviceList.length === 0" class="empty-state">
                <el-empty description="没有找到符合条件的设备" :image-size="200">
                    <template #image>
                        <el-icon class="empty-icon">
                            <Warning />
                        </el-icon>
                    </template>
                    <div class="mt-4 text-gray-500">
                        暂无离线或异常设备
                    </div>
                </el-empty>
            </div>

            <!-- 设备列表区域 -->
            <div v-else class="device-list">
                <!-- 离线设备 -->
                <div v-if="offlineDevices.length" class="device-group">
                    <h3 class="group-title">
                        <el-tag type="info" size="small">离线设备</el-tag>
                        <span class="device-count">{{ offlineDevices.length }}个</span>
                    </h3>
                    <div class="device-grid">
                        <div v-for="device in offlineDevices" :key="device.id" class="device-card">
                            <DeviceCard :device="device" :type="device.deviceType" />
                        </div>
                    </div>
                </div>

                <!-- 异常设备 -->
                <div v-if="errorDevices.length" class="device-group">
                    <h3 class="group-title">
                        <el-tag type="danger" size="small">异常设备</el-tag>
                        <span class="device-count">{{ errorDevices.length }}个</span>
                    </h3>
                    <div class="device-grid">
                        <div v-for="device in errorDevices" :key="device.id" class="device-card">
                            <DeviceCard :device="device" :type="device.deviceType" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { handleError } from '@/utils/handleError'
import { useRouter } from 'vue-router'
import DeviceCard from '../MeterManagement/components/DeviceCard.vue'
import DeviceStatusCards from '../MeterManagement/components/DeviceStatusCards.vue'
import { useCompanyStore } from '@/stores/company'
import { useMeterStore } from '@/stores/meter'
import { useAreaStore } from '@/stores/area'

const router = useRouter()
const companyStore = useCompanyStore()
const meterStore = useMeterStore()
const areaStore = useAreaStore()

const loading = ref(false)
const allDevices = ref([])

// 筛选表单数据
const filterForm = reactive({
    deviceStatus: '',
    deviceType: '',
    area: '',
    searchText: '',
})

// 处理状态卡片的点击筛选
const handleStatusFilter = (status) => {
    // 只保留离线和异常的筛选，忽略在线和全部
    if (status === 'offline' || status === 'error') {
        filterForm.deviceStatus = status
    } else {
        filterForm.deviceStatus = ''
    }
}

// 返回上一级
const handleBack = () => {
    router.back()
}

// 获取所有设备类型的数据并合并
const fetchAllDevices = async () => {
    if (!companyStore.currentCompany?.id) return

    loading.value = true
    try {
        // 获取类型为1的设备数据（水表）
        await meterStore.fetchMeterList({
            type: 1,
            company_id: companyStore.currentCompany.id
        })
        await meterStore.updateMeterStatus({
            id: companyStore.currentCompany.id
        })
        const type1Devices = processMeterData(meterStore.meterList, 1)

        // 获取类型为2的设备数据（电表）
        await meterStore.fetchMeterList({
            type: 2,
            company_id: companyStore.currentCompany.id
        })
        await meterStore.updateMeterStatus({
            id: companyStore.currentCompany.id
        })
        const type2Devices = processMeterData(meterStore.meterList, 2)

        // 获取类型为3的设备数据
        await meterStore.fetchMeterList({
            type: 3,
            company_id: companyStore.currentCompany.id
        })
        await meterStore.updateMeterStatus({
            id: companyStore.currentCompany.id
        })
        const type3Devices = processMeterData(meterStore.meterList, 3)

        // 合并所有设备数据
        allDevices.value = [...type1Devices, ...type2Devices, ...type3Devices]
            .filter(device => device.status === 'offline' || device.status === 'error')

    } catch (error) {
        handleError(error, "数据加载失败")
    } finally {
        loading.value = false
    }
}

// 转换原始表计数据为设备列表格式并添加设备类型标识
const processMeterData = (meters, deviceType) => {
    // 定义状态映射
    const STATUS_MAP = {
        1: 'offline',  // 离线
        2: 'online',   // 在线
        3: 'error'     // 异常
    }

    // 定义设备类型名称映射
    const TYPE_NAME_MAP = {
        1: '水表',
        2: '电表',
        3: '其他设备'
    }

    return meters.map(meter => ({
        id: meter.id,
        meter_code: meter.meter_code,
        status: STATUS_MAP[meter.status] || 'offline',
        area: areaStore.getAreaNameById(meter.area_id) || '未知区域',
        areaId: meter.area_id,
        location: meter.installation_location || '位置未知',
        voltage: '220V',
        current: '5A',
        pressure: deviceType === 1 ? '暂不支持' : undefined,
        level: meter.standard_coal_factor || 1,
        deviceType: deviceType,
        originalData: meter
    }))
}

// 筛选后的设备列表
const filteredDeviceList = computed(() => {
    return allDevices.value.filter(device => {
        // 状态筛选
        if (filterForm.deviceStatus && device.status !== filterForm.deviceStatus) {
            return false
        }

        // 设备类型筛选
        if (filterForm.deviceType && device.deviceType.toString() !== filterForm.deviceType) {
            return false
        }

        // 区域筛选
        if (filterForm.area && device.areaId !== filterForm.area) {
            return false
        }

        // 搜索文本筛选（设备ID、位置等）
        if (filterForm.searchText) {
            const searchLower = filterForm.searchText.toLowerCase()
            return device.meter_code.toLowerCase().includes(searchLower) ||
                device.location.toLowerCase().includes(searchLower) ||
                device.area.toLowerCase().includes(searchLower)
        }

        return true
    })
})

// 计算属性：按状态分组
const offlineDevices = computed(() =>
    filteredDeviceList.value.filter(device => device.status === 'offline')
)

const errorDevices = computed(() =>
    filteredDeviceList.value.filter(device => device.status === 'error')
)

watch(() => companyStore.currentCompany, fetchAllDevices, {
    immediate: true,
})
</script>

<style lang="scss" scoped>
.offline-error-devices-page {
    .page-title {
        display: flex;
        align-items: center;
        gap: var(--gap-small);
    }

    .content {
        padding: 0 var(--gap-normal);
    }

    .filter-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;

        .left-filters {
            display: flex;
            gap: var(--gap-normal);
            align-items: center;

            :deep(.el-select) {
                width: 150px;
            }

            :deep(.el-input) {
                width: 200px;
            }
        }
    }

    .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400px;
        margin-top: 40px;

        :deep(.el-empty) {
            .empty-icon {
                font-size: 100px;
                color: var(--el-color-danger);
                opacity: 0.5;
            }

            .el-empty__description {
                margin-top: 20px;
                font-size: var(--font-size-base);
                color: var(--el-color-text-secondary);
            }
        }
    }

    .device-group {
        margin-bottom: 32px;

        .group-title {
            margin: 0 0 16px;
            display: flex;
            align-items: center;
            gap: var(--gap-small);

            .device-count {
                color: var(--el-color-text-primary);
                font-size: 14px;
                font-weight: normal;
            }
        }
    }

    .device-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: var(--gap-normal);
    }
}
</style>